package com.example.demo.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.*;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.view.*;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.demo.R;

public class MainActivity extends AppCompatActivity {

    EditText mEditText;
    Context mContext = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = findViewById(R.id.edit);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.getMenuInflater().inflate(R.menu.menu, menu);//inflate膨胀
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.insert_image:
                insertImage();
                break;
            case R.id.insert_record:
                insertRecord();
                break;
        }
        return true;
    }

    public void insertImage() {
        //        Gson gson=new Gson();
        //        Test test1=gson.fromJson(JsonUtil.readJson("src/main/assets/ggbj_test.bean"), Test.class);
        //        Test test2=gson.fromJson(JsonUtil.readJson("src/main/assets/ggbj_test2.bean"), Test.class);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择图片");
        builder.setMessage("选择哪一张");
        builder.setCancelable(true);//使用back键是否可以取消该对话框
        builder.setPositiveButton("test1", (DialogInterface dialogInterface, int which) -> {
            showImage(BitmapFactory.decodeResource(getResources(), R.drawable.ok), false);
        });
        builder.setNegativeButton("test2", (DialogInterface dialogInterface, int which) -> {
            showImage(BitmapFactory.decodeResource(getResources(), R.drawable.ok), false);
        });
        AlertDialog dialog=builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
    }

    public void showImage(Bitmap pic, boolean isRecord) {

        if(!isRecord)
            pic = zoomImg(pic,getCurrentFocus().getWidth(),500);
        String img_str = "img";
        int start = mEditText.getSelectionStart();
        SpannableString ss = new SpannableString("\n"+img_str+"\n\n");
        ImageSpan imageSpan = new ImageSpan(mContext, pic);
        ss.setSpan(imageSpan, 1, img_str.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mEditText.getEditableText().insert(start, ss);// 设置ss要添加的位置

        //设置点击事件
        if (isRecord)
            setClick(start + 1, start + ss.length() - 2);

        mEditText.requestLayout();
        mEditText.requestFocus();
    }

    public void setClick(int start, int end) {
        mEditText.setMovementMethod(LinkMovementMethod.getInstance());
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                playMusic();
            }
        };
        mEditText.getEditableText().setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    public void insertRecord() {
        showImage(BitmapFactory.decodeResource(getResources(), R.drawable.play), true);
    }

    /**
     * 播放录音
     */
    public void playMusic() {
        MediaPlayer music = MediaPlayer.create(this, R.raw.record);
        music.start();
    }

    /**
     * 调整bitmap宽高
     * @param bm
     * @param newWidth
     * @param newHeight
     * @return
     */
    public Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }
}

